package com.example.base.tools

import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit


class TimerUtil {
    class Timer {
        var mDisposable: Disposable? = null

        /**
         * 执行定时任务
         * @param complete Function0<Unit>  倒计时结束时调用
         * @param block Function1<[@kotlin.ParameterName] Long, Unit>  心跳时调用
         * @param seconds Long  每次心跳间隔
         * @param repeat Long   倒计时多少秒
         *
         */
        fun timer(
            complete: () -> Unit,
            block: (t: Long) -> Unit,
            seconds: Long,
            repeat: Long
        ) {
            Observable.interval(0, seconds, TimeUnit.SECONDS)
                .take(repeat + 2)
                .map { repeat - it }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<Long> {
                    override fun onError(e: Throwable) {}
                    override fun onComplete() {
                        cancel()
                        complete()
                    }

                    override fun onNext(t: Long) {
                        block(t)
                    }

                    override fun onSubscribe(d: Disposable) {
                        mDisposable = d
                    }
                })
        }

        /**
         * 取消定时器
         */
        fun cancel() {
            if (mDisposable != null && !mDisposable!!.isDisposed) {
                mDisposable!!.dispose()
            }
        }

    }

}